import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

// 登录注册页面组件
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'

// 用户端组件 - 布局组件保留在components，页面组件移至views
import UserDashboard from '../views/user/UserDashboard.vue'
import UserLayout from '../components/user/UserLayout.vue'
import HealthDataForm from '../views/user/HealthDataForm.vue'
import DataHistory from '../views/user/DataHistory.vue'
import PredictionResults from '../views/user/PredictionResults.vue'
import UserProfile from '../views/user/UserProfile.vue'

// 统计员端组件 - 布局组件保留在components，页面组件移至views
import StatisticianLayout from '../components/statistician/StatisticianLayout.vue'
import SystemFeedback from '../views/statistician/SystemFeedback.vue'
import StatisticianProfile from '../views/statistician/StatisticianProfile.vue'

// 管理员端组件 - 布局组件保留在components，页面组件移至views
import AdminLayout from '../components/admin/AdminLayout.vue'
import AdminDashboard from '../views/admin/AdminDashboard.vue'
import UserManagement from '../views/admin/UserManagement.vue'
import StatisticianManagement from '../views/admin/StatisticianManagement.vue'
import SystemConfiguration from '../views/admin/SystemConfiguration.vue'
import AdminProfile from '../views/admin/AdminProfile.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    // 法律条款相关路由
    {
      path: '/privacy-policy',
      name: 'privacyPolicy',
      component: () => import('../views/PrivacyPolicy.vue')
    },
    {
      path: '/user-agreement',
      name: 'userAgreement',
      component: () => import('../views/UserAgreement.vue')
    },
    {
      path: '/disclaimer',
      name: 'disclaimer',
      component: () => import('../views/Disclaimer.vue')
    },
    // 普通用户路由
    {
      path: '/user',
      meta: { requiresAuth: true, role: 'user' },
      component: UserLayout,
      children: [
        {
          path: 'dashboard',
          name: 'userDashboard',
          component: UserDashboard
        },
        {
          path: 'health-data',
          name: 'healthData',
          component: HealthDataForm
        },
        {
          path: 'data-history',
          name: 'dataHistory',
          component: DataHistory
        },
        {
          path: 'predictions',
          name: 'predictions',
          component: PredictionResults
        },
        {
          path: 'profile',
          name: 'userProfile',
          component: UserProfile
        },
        {
          path: 'system-feedback',
          name: 'userSystemFeedback',
          component: SystemFeedback
        }
      ]
    },
    // 疾控统计员路由
    {
      path: '/statistician',
      meta: { requiresAuth: true, role: 'statistician' },
      component: StatisticianLayout,
      children: [
        {
          path: 'health-data-dashboard',
          name: 'statisticianHealthDataDashboard',
          component: () => import('../views/statistician/HealthDataDashboard.vue')
        },
        {
          path: 'data-export',
          name: 'dataExport',
          component: SystemFeedback
        },
        {
          path: 'profile',
          name: 'statisticianProfile',
          component: StatisticianProfile
        }
      ]
    },
    // 系统管理员路由
    {
      path: '/admin',
      meta: { requiresAuth: true, role: 'admin' },
      component: AdminLayout,
      children: [
        {
          path: 'dashboard',
          name: 'adminDashboard',
          component: AdminDashboard
        },
        {
          path: 'user-management',
          name: 'userManagement',
          component: UserManagement
        },
        {
          path: 'statistician-management',
          name: 'statisticianManagement',
          component: StatisticianManagement
        },
        {
          path: 'health-indicators',
          name: 'healthIndicators',
          component: () => import('../views/admin/HealthIndicators.vue')
        },
        {
          path: 'system-config',
          name: 'systemConfig',
          component: SystemConfiguration
        },
        {
          path: 'profile',
          name: 'adminProfile',
          component: AdminProfile
        }
      ]
    }
  ]
})

// 路由守卫，验证用户权限
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 需要登录的路由
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      next('/login')
    } else if (to.meta.role && to.meta.role !== userStore.role) {
      // 检查角色权限 - 已登录但角色不匹配时重定向到对应角色首页
      const redirectMap = {
        user: '/user/dashboard',
        statistician: '/statistician/health-data-dashboard',
        admin: '/admin/dashboard'
      }
      next(redirectMap[userStore.role] || '/login')
    } else {
      next()
    }
  } else {
    // 不需要登录的路由（如登录页、注册页、法律条款页面）
    // 特殊处理：确保法律条款页面在任何情况下都能正常访问
    const legalPages = ['privacyPolicy', 'userAgreement', 'disclaimer']
    if (legalPages.includes(to.name)) {
      next()
    } else if (userStore.isLoggedIn) {
      // 已登录用户访问其他非认证页面时重定向到对应首页
      switch (userStore.role) {
        case 'user':
          next('/user/dashboard')
          break
        case 'statistician':
          next('/statistician/health-data-dashboard')
          break
        case 'admin':
          next('/admin/dashboard')
          break
        default:
          // 默认情况也要调用next()防止路由阻塞
          next()
          break
      }
    } else {
      next()
    }
  }
})

export default router
